package com.pehulja.mmdo.coursework.math.old;
import java.util.*;


public class Polynomial implements Function  {

protected List <Term> list;
	public Polynomial(Function temp)
	{
		list=new ArrayList<Term>();
		
			for(Term i:((Polynomial) temp).list)
				this.list.add(new Term(i.getFactor(), i.getDegree()));
		
	}
	public Polynomial(int [][] tempList)
	{
		list=new LinkedList<Term>();
		for(int [] i : tempList)
			list.add(new Term(i[0], i[1]));
	}
	public Polynomial()
	{
		list=new LinkedList<Term>();
	}
	
	public void add(Term el)
	{
		list.add(el);
		simplify();
	}
	public void add(Function func)
	{
		
		for(int i=0; i<((Polynomial)func).getCountTerms(); i++)
			list.add(((Polynomial)func).getTermAt(i));
		simplify();
	}
	public Term getTermAt(int i)
	{
		return list.get(i);
	}
	public void add(String temp)
	{
		list.add(new Term(temp));
		simplify();
	}
	public void add(double factor, int degree)
	{
		list.add(new Term(factor, degree));
		simplify();
	}
	public void add()
	{
		list.add(new Term());
	}
	public String toString() 
	{
		 StringBuffer temp=new StringBuffer();
		 temp.append('[');
		 for(Term el:list)
			 if(!el.toString().equals(""))
				 temp.append('+'+el.toString());
		 temp.append(']');
		 String temp1=new String(temp);
		 return temp1;
	}
	public int getCountTerms()
	{
		return list.size();
	}
	
	public static Function multiply(Function a, Function b)
	{
		Polynomial c=new Polynomial();
		
		for(Term i:((Polynomial)b).list)
			for(Term j:((Polynomial)a).list)
				c.add(i.getFactor()*j.getFactor(), i.getDegree()+j.getDegree());
		simplify(c);
		return c;
	}
	public double getFunctionValue(double x)
	{
		double y=0;
		for(Term t:list)
			y+=t.getFactor()*(Math.pow(x, t.getDegree()));
		return y;
	}
	public void simplify()
	{
		@SuppressWarnings("unused")
		String a=list.get(0).toString();
		if(!list.isEmpty())
		{
			for(int i=0; i<list.size(); i++)
				if(list.get(i).getFactor()==0)
					list.remove(i);
			for(int i=0; i<list.size(); i++)
			{
				int degree=list.get(i).getDegree();
				for(int j=0; j<list.size(); j++)
					if(degree==list.get(j).getDegree() && j!=i)
					{
						list.get(i).setFactor(list.get(i).getFactor()+list.get(j).getFactor());
						list.remove(j);
						j--;
					}
			}
			if(list.size()==0)
				list.add(new Term(0, 0));
		}
	}
	public static void simplify(Polynomial t)
	{
		t.simplify();
	}
}
